package com.cango.student.lthread;

import java.util.PriorityQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TwoThreadCodition {
    private int start = 1;
    private Lock lock = new ReentrantLock();
//    private Condition j = lock.newCondition();
    private Condition o = lock.newCondition();
    private boolean flg = false;
    public static void main(String[] args) {
        TwoThreadCodition twoThread = new TwoThreadCodition();

        Thread t1 = new Thread(new OuNum(twoThread));
        t1.setName("A");


        Thread t2 = new Thread(new JiNum(twoThread));
        t2.setName("B");

        t1.start();
        t2.start();
    }

    /**
     * 偶数线程
     */
    public static class OuNum implements Runnable {
        private TwoThreadCodition number;

        public OuNum(TwoThreadCodition number) {
            this.number = number;
        }

        @Override
        public void run() {

            while (number.start < 100) {
                number.lock.lock();
                try {
                    while (!number.flg) {
                        try {
                            number.o.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "+-+偶数" + number.start);
                    number.start++;
                    number.flg=false;
//                    number.j.signal();
                    number.o.signal();

                } finally {
                    number.lock.unlock();
                }
            }
        }
    }


    /**
     * 奇数线程
     */
    public static class JiNum implements Runnable {
        private TwoThreadCodition number;

        public JiNum(TwoThreadCodition number) {
            this.number = number;
        }

        @Override
        public void run() {
            while (number.start < 100) {
                number.lock.lock();
                try {
                    while (number.flg) {
                        try {
//                            number.j.await();
                            number.o.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName() + "+-+奇数" + number.start);
                    number.start++;
                    number.flg=true;
                    number.o.signal();
                } finally {
                    number.lock.unlock();
                }
            }
        }
    }
}
